{% extends "rbac/base.html" %}

{% block extra_css %}
<style>
/* 角色管理页面专用样式 */
.role-table {
    border-collapse: separate;
    border-spacing: 0;
}

.role-table thead th {
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    font-weight: 600;
}

.role-table tbody tr:hover {
    background-color: rgba(13, 110, 253, 0.05);
}

.role-table th, .role-table td {
    padding: 1rem;
    vertical-align: middle;
}

.role-name {
    font-weight: 500;
}

.role-code {
    font-family: 'Courier New', monospace;
    font-size: 0.875rem;
}

.role-description {
    color: #6c757d;
    font-size: 0.875rem;
}

.role-permissions-count {
    display: inline-block;
    min-width: 30px;
    text-align: center;
}

.role-status-badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}

.role-actions .btn {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    margin-right: 0.25rem;
}

.role-actions .btn:last-child {
    margin-right: 0;
}

.empty-state {
    padding: 3rem 2rem;
    text-align: center;
}

.search-container {
    max-width: 300px;
}

/* 响应式优化 */
@media (max-width: 768px) {
    .role-table th, .role-table td {
        padding: 0.75rem 0.5rem;
    }
    
    .role-description {
        display: none;
    }
    
    .role-actions .btn span {
        display: none;
    }
    
    .role-actions .btn i {
        margin-right: 0;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <!-- 页面标题区 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2 class="mb-1"><i class="fas fa-users-cog text-primary me-2"></i>角色管理</h2>
                    <p class="text-muted mb-0">管理系统角色和权限分配</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="{% url 'rbac:permission_list' %}" class="btn btn-outline-primary">
                        <i class="fas fa-key me-1"></i>权限管理
                    </a>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal">
                        <i class="fas fa-plus me-1"></i>添加角色
                    </button>
                </div>
            </div>
            
            <!-- 消息提示 -->
            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                        <i class="fas fa-info-circle me-2"></i>{{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
            
            <!-- 角色列表 -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <h5 class="mb-0 text-dark">
                                <i class="fas fa-list me-2 text-primary"></i>角色列表
                            </h5>
                            <span class="badge bg-light text-dark ms-2">{{ roles|length }} 个角色</span>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <div class="input-group search-container">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" id="roleSearchInput" 
                                       placeholder="搜索角色名称或代码...">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if roles %}
                        <div class="table-responsive">
                            <table class="table role-table mb-0">
                                <thead>
                                    <tr>
                                        <th>角色名称</th>
                                        <th>角色代码</th>
                                        <th>描述</th>
                                        <th>类型</th>
                                        <th>权限数</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="roleTableBody">
                                    {% for role in roles %}
                                    <tr class="role-row" data-role-name="{{ role.name|lower }}" data-role-code="{{ role.code|lower }}">
                                        <td>
                                            <div class="role-name">
                                                {% if role.is_system %}
                                                    <i class="fas fa-shield-alt text-primary me-1"></i>
                                                {% else %}
                                                    <i class="fas fa-user-tag text-secondary me-1"></i>
                                                {% endif %}
                                                {{ role.name }}
                                            </div>
                                        </td>
                                        <td>
                                            <code class="role-code text-primary">{{ role.code }}</code>
                                        </td>
                                        <td>
                                            <div class="role-description">{{ role.description|default:"暂无描述" }}</div>
                                        </td>
                                        <td>
                                            {% if role.is_system %}
                                                <span class="badge bg-primary bg-opacity-10 text-primary">
                                                    <i class="fas fa-cog me-1"></i>系统角色
                                                </span>
                                            {% else %}
                                                <span class="badge bg-secondary bg-opacity-10 text-secondary">
                                                    <i class="fas fa-user me-1"></i>自定义
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <span class="badge bg-info bg-opacity-10 text-info role-permissions-count">
                                                {{ role.permissions.count }}
                                            </span>
                                        </td>
                                        <td>
                                            {% if role.is_active %}
                                                <span class="badge bg-success role-status-badge">
                                                    <i class="fas fa-check me-1"></i>激活
                                                </span>
                                            {% else %}
                                                <span class="badge bg-danger role-status-badge">
                                                    <i class="fas fa-times me-1"></i>禁用
                                                </span>
                                            {% endif %}
                                        </td>
                                        <td class="role-actions">
                                            <button type="button" class="btn btn-primary btn-sm" 
                                                    onclick="managePermissions({{ role.id }}, '{{ role.name }}')" 
                                                    title="管理权限">
                                                <i class="fas fa-key me-1"></i><span>权限</span>
                                            </button>
                                            <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                    onclick="editRole({{ role.id }}, '{{ role.name }}', '{{ role.code }}', '{{ role.description }}', {{ role.is_system|yesno:'true,false' }})" 
                                                    title="编辑角色">
                                                <i class="fas fa-edit me-1"></i><span>编辑</span>
                                            </button>
                                            <button type="button" class="btn btn-outline-danger btn-sm" 
                                                    onclick="deleteRole({{ role.id }}, '{{ role.name }}', {{ role.is_system|yesno:'true,false' }})" 
                                                    title="删除角色">
                                                <i class="fas fa-trash me-1"></i><span>删除</span>
                                            </button>
                                            <button type="button" class="btn btn-outline-{% if role.is_active %}warning{% else %}success{% endif %} btn-sm" 
                                                    onclick="toggleRoleStatus({{ role.id }}, {{ role.is_active|yesno:'true,false' }})" 
                                                    title="{% if role.is_active %}禁用{% else %}启用{% endif %}角色">
                                                {% if role.is_active %}
                                                    <i class="fas fa-ban me-1"></i><span>禁用</span>
                                                {% else %}
                                                    <i class="fas fa-check me-1"></i><span>启用</span>
                                                {% endif %}
                                            </button>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-5">
                            <div class="empty-state">
                                <i class="fas fa-users-slash fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted mb-2">暂无角色数据</h5>
                                <p class="text-muted mb-4">系统中还没有创建任何角色，点击下方按钮开始创建</p>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal">
                                    <i class="fas fa-plus me-1"></i>创建第一个角色
                                </button>
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加角色模态框 -->
<div class="modal fade" id="addRoleModal" tabindex="-1" aria-labelledby="addRoleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white border-0">
                <h5 class="modal-title" id="addRoleModalLabel">
                    <i class="fas fa-plus-circle me-2"></i>添加新角色
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <form id="addRoleForm">
                    <div class="mb-3">
                        <label for="roleName" class="form-label fw-medium">
                            <i class="fas fa-tag text-primary me-1"></i>角色名称 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-lg" id="roleName" 
                               placeholder="请输入角色名称" required>
                        <div class="form-text">用于显示的角色名称，如“部门管理员”</div>
                    </div>
                    <div class="mb-3">
                        <label for="roleCode" class="form-label fw-medium">
                            <i class="fas fa-code text-info me-1"></i>角色代码 
                            <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control form-control-lg" id="roleCode" 
                               placeholder="英文代码，如：department_manager" required>
                        <div class="form-text">唯一标识码，只能包含字母、数字和下划线</div>
                    </div>
                    <div class="mb-0">
                        <label for="roleDescription" class="form-label fw-medium">
                            <i class="fas fa-file-alt text-secondary me-1"></i>角色描述
                        </label>
                        <textarea class="form-control" id="roleDescription" rows="3" 
                                  placeholder="请描述该角色的职责和功能（可选）"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer border-0 bg-light">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" onclick="saveRole()">
                    <i class="fas fa-save me-1"></i>保存角色
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 权限管理模态框 -->
<div class="modal fade" id="permissionModal" tabindex="-1" aria-labelledby="permissionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white border-0">
                <h5 class="modal-title" id="permissionModalLabel">
                    <i class="fas fa-key me-2"></i>权限管理 - <span id="roleNameTitle"></span>
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" id="currentRoleId">
                
                <!-- 快速操作栏 -->
                <div class="d-flex justify-content-between align-items-center mb-4 p-3 bg-light rounded">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-magic text-primary me-2"></i>
                        <h6 class="mb-0 text-dark">快速操作</h6>
                    </div>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllPermissions()">
                            <i class="fas fa-check-double me-1"></i>全选
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="deselectAllPermissions()">
                            <i class="fas fa-eraser me-1"></i>清空
                        </button>
                    </div>
                </div>
                
                <!-- 权限分组列表 -->
                <div class="accordion" id="permissionAccordion">
                    {% for group, perms in permission_groups.items %}
                    <div class="accordion-item border-0 shadow-sm mb-2">
                        <h2 class="accordion-header" id="heading{{ forloop.counter }}">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" 
                                    data-bs-target="#collapse{{ forloop.counter }}" aria-expanded="false" 
                                    aria-controls="collapse{{ forloop.counter }}">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-layer-group text-primary me-2"></i>
                                    <strong class="text-dark">{{ group }}</strong>
                                    <span class="badge bg-primary bg-opacity-10 text-primary ms-2">
                                        {{ perms|length }} 个权限
                                    </span>
                                </div>
                            </button>
                        </h2>
                        <div id="collapse{{ forloop.counter }}" class="accordion-collapse collapse" 
                             aria-labelledby="heading{{ forloop.counter }}" data-bs-parent="#permissionAccordion">
                            <div class="accordion-body">
                                <!-- 分组操作按钮 -->
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="mb-0 text-dark">
                                        <i class="fas fa-folder text-warning me-1"></i>{{ group }}
                                    </h6>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" class="btn btn-outline-primary" 
                                                onclick="selectAllInGroup('{{ group }}')">
                                            <i class="fas fa-check me-1"></i>全选
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary" 
                                                onclick="deselectAllInGroup('{{ group }}')">
                                            <i class="fas fa-times me-1"></i>取消
                                        </button>
                                    </div>
                                </div>
                                
                                <!-- 权限列表 -->
                                <div class="row g-3">
                                    {% for perm in perms %}
                                    <div class="col-md-6">
                                        <div class="form-check p-3 bg-white border rounded">
                                            <input class="form-check-input permission-checkbox" 
                                                   type="checkbox" 
                                                   value="{{ perm.id }}" 
                                                   id="perm_{{ perm.id }}"
                                                   data-group="{{ group }}">
                                            <label class="form-check-label w-100" for="perm_{{ perm.id }}">
                                                <div class="permission-item">
                                                    <strong class="text-dark d-block">{{ perm.name }}</strong>
                                                    <small class="text-muted d-block mb-1">{{ perm.description }}</small>
                                                    <code class="small text-primary">{{ perm.code }}</code>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            <div class="modal-footer border-0 bg-light">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" onclick="savePermissions()">
                    <i class="fas fa-save me-1"></i>保存权限配置
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// 添加角色
function saveRole() {
    const name = document.getElementById('roleName').value.trim();
    const code = document.getElementById('roleCode').value.trim();
    const description = document.getElementById('roleDescription').value.trim();
    
    if (!name || !code) {
        alert('角色名称和代码不能为空');
        return;
    }
    
    // 显示加载状态
    const saveBtn = event.target;
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
    saveBtn.disabled = true;
    
    fetch('{% url "rbac:role_add" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            name: name,
            code: code,
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ 角色创建成功！');
            const modal = bootstrap.Modal.getInstance(document.getElementById('addRoleModal'));
            modal.hide();
            location.reload();
        } else {
            alert('❌ 创建失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    })
    .finally(() => {
        saveBtn.innerHTML = originalText;
        saveBtn.disabled = false;
    });
}

// 权限管理
function managePermissions(roleId, roleName) {
    document.getElementById('currentRoleId').value = roleId;
    document.getElementById('roleNameTitle').textContent = roleName;
    
    // 清除所有复选框
    document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = false);
    
    // 获取角色权限
    fetch(`{% url 'rbac:get_role_permissions' 0 %}`.replace('0', roleId))
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            data.permission_ids.forEach(permId => {
                const checkbox = document.getElementById('perm_' + permId);
                if (checkbox) checkbox.checked = true;
            });
        }
    })
    .catch(error => {
        console.error('获取权限失败:', error);
    });
    
    // 使用Bootstrap 5 API显示模态框
    const modal = new bootstrap.Modal(document.getElementById('permissionModal'));
    modal.show();
}

// 保存权限
function savePermissions() {
    const roleId = document.getElementById('currentRoleId').value;
    const checkedBoxes = document.querySelectorAll('.permission-checkbox:checked');
    const permissionIds = Array.from(checkedBoxes).map(cb => cb.value);
    
    const saveBtn = event.target;
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
    saveBtn.disabled = true;
    
    fetch(`{% url 'rbac:role_manage_permissions' 0 %}`.replace('0', roleId), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            permission_ids: permissionIds
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ 权限分配成功！');
            const modal = bootstrap.Modal.getInstance(document.getElementById('permissionModal'));
            modal.hide();
            location.reload();
        } else {
            alert('❌ 权限分配失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    })
    .finally(() => {
        saveBtn.innerHTML = originalText;
        saveBtn.disabled = false;
    });
}

// 权限组操作
function selectAllInGroup(group) {
    document.querySelectorAll(`[data-group="${group}"]`).forEach(cb => cb.checked = true);
}

function deselectAllInGroup(group) {
    document.querySelectorAll(`[data-group="${group}"]`).forEach(cb => cb.checked = false);
}

function selectAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = true);
}

function deselectAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = false);
}

// 编辑角色
function editRole(roleId, name, code, description, isSystem) {
    // 系统角色的特殊提示
    if (isSystem) {
        if (!confirm('⚠️ 您正在编辑系统角色 "' + name + '"\n\n系统角色的修改可能影响系统稳定性，请谨慎操作。\n确认继续吗？')) {
            return;
        }
    }
    
    // 使用prompt的简单编辑方式（因为模态框可能不存在）
    const newName = prompt('请输入新的角色名称：', name);
    if (!newName || newName.trim() === '') {
        alert('角色名称不能为空');
        return;
    }
    
    const newCode = prompt('请输入新的角色代码：', code);
    if (!newCode || newCode.trim() === '') {
        alert('角色代码不能为空');
        return;
    }
    
    const newDescription = prompt('请输入新的角色描述（可选）：', description || '');
    
    fetch(`{% url 'rbac:role_edit' 0 %}`.replace('0', roleId), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            name: newName.trim(),
            code: newCode.trim(),
            description: newDescription ? newDescription.trim() : ''
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ 角色更新成功！');
            location.reload();
        } else {
            alert('❌ 更新失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    });
}

// 删除角色
function deleteRole(roleId, roleName, isSystem) {
    let confirmMessage = `⚠️ 确认删除角色 "${roleName}" 吗？\n\n此操作不可逆转！`;
    
    // 系统角色的特殊警告
    if (isSystem) {
        confirmMessage = `⚠️ 危险操作：删除系统角色 "${roleName}"\n\n系统角色是系统的核心组件，删除可能导致：\n• 系统功能异常\n• 权限管理混乱\n• 数据一致性问题\n\n仅建议在测试环境下执行此操作！\n\n仍要继续吗？`;
    }
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    // 系统角色的二次确认
    if (isSystem) {
        const userInput = prompt('请输入 "YES" 来最终确认删除系统角色：');
        if (userInput !== 'YES') {
            alert('操作已取消');
            return;
        }
    }
    
    fetch(`{% url 'rbac:role_delete' 0 %}`.replace('0', roleId), {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ 角色已删除');
            location.reload();
        } else {
            alert('❌ 删除失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    });
}

// 切换角色状态
function toggleRoleStatus(roleId, isActive) {
    const action = isActive ? '禁用' : '启用';
    if (!confirm(`确认${action}该角色吗？`)) {
        return;
    }
    
    fetch(`{% url 'rbac:role_toggle_status' 0 %}`.replace('0', roleId), {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ ' + data.message);
            location.reload();
        } else {
            alert('❌ 操作失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    });
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 清空表单当模态框隐藏时
    document.getElementById('addRoleModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('addRoleForm').reset();
    });
    
    document.getElementById('permissionModal').addEventListener('hidden.bs.modal', function() {
        // 清空权限选择
        document.querySelectorAll('.permission-checkbox').forEach(cb => cb.checked = false);
        document.getElementById('currentRoleId').value = '';
        document.getElementById('roleNameTitle').textContent = '';
    });
    
    // 搜索功能
    const searchInput = document.getElementById('roleSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            const roleCards = document.querySelectorAll('.role-card');
            
            roleCards.forEach(card => {
                const roleName = card.dataset.roleName || '';
                const roleCode = card.dataset.roleCode || '';
                
                if (roleName.includes(searchTerm) || roleCode.includes(searchTerm)) {
                    card.style.display = 'block';
                    card.style.opacity = '1';
                } else {
                    card.style.display = 'none';
                    card.style.opacity = '0';
                }
            });
            
            // 显示搜索结果统计
            const visibleCards = document.querySelectorAll('.role-card[style*="display: block"], .role-card:not([style*="display: none"])');
            console.log(`搜索 "${searchTerm}" 找到 ${visibleCards.length} 个角色`);
        });
    }
    
    console.log('🎉 角色管理页面初始化完成');
});
</script>
{% endblock %}